package br.com.escolaespacocrianca.fineec.business;

import java.util.ArrayList;
import java.util.List;

import br.com.caelum.vraptor.ioc.Component;
import br.com.escolaespacocrianca.fineec.model.Enrollment;
import br.com.escolaespacocrianca.fineec.model.ExtraService;
import br.com.escolaespacocrianca.fineec.model.Month;
import br.com.escolaespacocrianca.fineec.model.Plot;
import br.com.escolaespacocrianca.fineec.model.enums.EnrollmentStatus;
import br.com.escolaespacocrianca.fineec.model.query.Bill;

@Component
public class QueryBusiness {
	
	private EnrollmentBusiness enrollmentBusiness;
	
	public QueryBusiness(EnrollmentBusiness enrollmentBusiness) {
		
		this.enrollmentBusiness = enrollmentBusiness;
	}
	
	public List<Bill> listBill(Month month, int year){
		
		List<Bill> bills = new ArrayList<Bill>();
		for(Enrollment enrollment:enrollmentBusiness.searchByStatus(EnrollmentStatus.FINISHED)){
			if (enrollment.getYear() == year ){
			
				Bill bill = new Bill();
				bill.setEnrollment(enrollment);
				double totalPrice = 0;
				
				boolean hasPayment = false;
				for (Plot plot : enrollment.getPlots()) {
					if (!plot.isDeleted()){
						if (plot.getMonth() == month){
							totalPrice += plot.getPrice();
							hasPayment = true;
						}
					}
				}
				
				for (ExtraService extraService : enrollment.getExtraServices()) {
					for (Plot plot: extraService.getPlots()) {
						if (!plot.isDeleted()){
							if (plot.getMonth() == month){
								totalPrice += plot.getPrice();
								hasPayment = true;
							}
						}
					}
				}
				
				bill.setPrice(totalPrice);
				
				if(hasPayment){
					bills.add(bill);
				}
			}
		}
		return bills;
	}

	public List<Bill> listBillForEnrollment(Enrollment enrollment) {
		List<Bill> bills = new ArrayList<Bill>();
		Enrollment enrollmentFull = enrollmentBusiness.find(enrollment.getId());
		
		for (Month month : Month.values()) {
		
			Bill bill = new Bill();
			bill.setEnrollment(enrollmentFull);
			bill.setMonth(month);
			double totalPrice = 0;
			
			boolean hasPayment = false;
			for (Plot plot : enrollmentFull.getPlots()) {
				if (!plot.isDeleted()){
					if (plot.getMonth() == month){
						totalPrice += plot.getPrice();
						hasPayment = true;
					}
				}
			}
			
			for (ExtraService extraService : enrollmentFull.getExtraServices()) {
				for (Plot plot: extraService.getPlots()) {
					if (!plot.isDeleted()){
						if (plot.getMonth() == month){
							totalPrice += plot.getPrice();
							hasPayment = true;
						}
					}
				}
			}
			
			bill.setPrice(totalPrice);
			
			if(hasPayment){
				bills.add(bill);
			}
		}
		
		return bills;
	}
	
}
